/*
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 */
var EditSales = {
    ssUrl:'EditSales/add',
    selected_row_id:null,

    /* dataTable Object */
    objGrid:null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;


        Calendar.setup({
            inputField : "purchased_date",
            trigger    : "purchased_date_btn",
            onSelect   : function() { this.hide() },
            dateFormat: "%B %d, %Y",
            showTime: false,
            animation: true
        });

        /*Sortable Table */
        var oTable = null;
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url:dataUrl,
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Purchased Date', name:'purchased_date', width:100, sortable:true, align:'center', hide:false},
                {display:'Customer', name:'customer_id', width:200, sortable:true, align:'center', hide:false},
                {display:'Sales No.', name:'invoice_number', width:100, sortable:true, align:'center', hide:false},
                {display:'Vehicle No.', name:'vehicle_no', width:100, sortable:true, align:'center', hide:false},
                {display:'Product Names', name:'pr_name', width:200, sortable:true, align:'center', hide:false},
                //{display: 'Duration in Month', name : 'dm', width : 100, sortable : false, align: 'center', hide:false},
                //{display: 'Items Purchased', name : 'ip', width : 100, sortable : false, align: 'center', hide:false},
                {display:'Cost', name:'cost', width:80, sortable:false, align:'center', hide:false},
                {display:'Interest %', name:'interest', width:60, sortable:false, align:'center', hide:false},
                {display:'Total Periods', name:'period', width:90, sortable:false, align:'center', hide:false}
                //{display:'Openining Bal', name:'open_bal', width:170, sortable:false, align:'center', hide:false},
                //{display:'Installment', name:'installment', width:100, sortable:false, align:'center', hide:false},
                //{display:'Total Repayment', name : 'total_installment', width : 110, sortable : false, align: 'center', hide:false},
                //{display:'Balance', name:'balance', width:80, sortable:false, align:'center', hide:false}
                //{display: 'Last Month Paid ', name : 'lmp', width : 100, sortable : false, align: 'center', hide:false},
                //{display: 'Next Credit Date', name : 'ncd', width : 100, sortable : false, align: 'center', hide:false},
                //{display: 'Comment', name : 'comments', width : 100, sortable : false, align: 'center', hide:false}
            ],
            formFields:[
                /*{type:'buttom', name:'View Details', bclass:'view', onpress:self.handleGridEvent},
                {separator:true},*/
                {type:'buttom', name:'Edit Sale', bclass:'edit', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom',name: 'Delete', bclass: 'delete', onpress : self.handleGridEvent},
                {separator: true},
                /*{type:'buttom',name: 'Reprint Invoice', bclass: 'print', onpress : self.handleGridEvent},
                {separator: true},*/
                {type:'select', name:'Select Cutomers', id:'select_customer' ,bclass:'person', options:gbl_customers_sales , onchange:self.handleGridEvent}
            ],
            /*searchitems : [
             {display: 'Name', name : 'name', isdefault: true}
             ],*/
            checkboxSelection:true,
            columnControl:true,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300,
            onSubmit: self.addFormData
        });

        $('#form #original_deposit_amt').focusout(function () {
            var currency = $('#form #currency').val();
            var deposit_currency = $('#form #deposit_currency').val();
            var amount = $('#form #original_deposit_amt').val();
            var usd_rate = $('#form #usd_rate').val();
            self.getDeposit(currency, deposit_currency, amount, usd_rate);
            $.colorbox.resize();
        });
        $('#form #deposit_currency').change(function () {
            var currency = $('#form #currency').val();
           // var deposit_currency = $('#form #deposit_currency').val();
            var amount = $('#form #original_deposit_amt').val();
            var usd_rate = $('#form #usd_rate').val();
            self.getDeposit(currency, $(this).val(), amount, usd_rate);
            $.colorbox.resize();
        });

        /** Credit Section **/

        $('#save-btn').click(function () {
            self.save();
        });

        $('#cancel-btn').click(function () {
            $.colorbox.close();
            self.selected_row_id = null;
        });

       /* $('#credit-close-btn').click(function () {
            $.colorbox.close();
        });*/

        /** Update the total cost if there is a change in quantity **/
       /* $('#credit-form-window #credit-form #quantity').focusout(function () {
            var value = parseFloat($(this).val());
            var old_amt = parseFloat($('#credit-form-window #credit-form #cost').val());
            if (value == 0) {
                value = 1;
                $(this).val(1);
            }
            var new_amt = old_amt * value;
            $('#credit-form-window #credit-form #cost').val(new_amt.toFixed(2));
        });*/

        /** On change on equipmemnt bought **/
       /* $('#credit-form-window #credit-form #equipment_id').change(function () {
            var id = $(this).val();
            var amount = parseFloat(global_equipment_data[id]['amount']);
            var quantity = parseFloat($('#credit-form-window #credit-form #quantity').val());
            var amt = amount * quantity;
            $('#credit-form-window #credit-form #cost').val(amt.toFixed(2));
        });*/

        self.initDataTypeMenus();
    },

    handleGridEvent:function (com, grid, json) {
        if (com == 'View Details') {
            if (jLib.rowSelectedCheck(grid, 1)) {
                EditSales.view(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Edit Sale') {
            if(jLib.rowSelectedCheck(grid,1)){
                EditSales.editSale(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Delete') {
            if(jLib.rowSelectedCheck(grid)){
                EditSales.delete_(grid);
            }
        }
        else if (com == 'Reprint Invoice') {
            if(jLib.rowSelectedCheck(grid, 1)){
                EditSales.reprint_invoice(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Select Cutomers') {
            EditSales.filterCustomers(json);
        }
    },

    filterCustomers:function(value){
        var self = this;
        self.objGrid.flexOptions({params: [{name:'customer_id',value:value}]}).flexReload();
        return false;
    },

    addFormData:function(){
        var self = this;
        var val = $("#select_customer").val();
        //self.objGrid.flexOptions({params: [{name:'customer_id',value:val}]});
        $('#creditflex').flexOptions({params: [{name:'customer_id',value:val}]});
        return true;
    },

    view:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];
        var url = $('#load-sale-url').val();
        var query = 'type=load&data-id=' + dataID;
        $.post(url, query, function (response) {
            if (response.code === 0) {
                var dataObj = response.data;
                var currency = dataObj['Sale']['currency'];

                $('#view-window td span.name').html(dataObj['Customer']['name']);
                $('#view-window td span.items').html(dataObj['SaleItem'][0]['Item']['name']);
                $('#view-window td span.vehicle_no').html(dataObj['Sale']['vehicle_no']);
                $('#view-window td span.purchased_date').html(dataObj['Sale']['purchased_date']);
                $('#view-window td span.cost').html(currency+" "+dataObj['Sale']['cost']);
                $('#view-window td span.insurance_total').html(currency+" "+dataObj['Sale']['insurance_total']);
                $('#view-window td span.discount').html(dataObj['Sale']['discount']);
                $('#view-window td span.deposit').html(currency+" "+dataObj['Sale']['deposit']);
                $('#view-window td span.principal').html(currency+" "+dataObj['Sale']['principal']);
                $('#view-window td span.duration_in_month').html(dataObj['Sale']['duration_in_month']);
                $('#view-window td span.interest').html(dataObj['Sale']['interest']);
                $('#view-window td span.tenor').html(dataObj['Sale']['tenor']);
                $('#view-window td span.comments').html(dataObj['Sale']['comments']);

                self.selected_row_id = dataID;

                $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'Sales Detail Information',
                    href:"#view-window"
                });
            }
            /* When there are Errors */
            else if (response.code === 1) {
                /* Alert the user that the server response*/
                jLib.serverError(response.mesg);
            }
        }, 'json');
    },

    getDeposit:function(currency, deposit_currency, deposit_value, usd_rate){
        var self = this;

        if(deposit_value == 0){
            return;
        }
        //console.log('transaction curency '+currency);
        //console.log('deposite currency '+deposit_currency);
        //console.log('deposit '+deposit_value);
        //console.log('rate '+usd_rate);

        if(deposit_currency == currency){
            $('#form #deposit_conversion_rate_txt').hide();
            $('#form #conversion_rate_txt').hide();
        }
        else{
            if(currency == '$' && deposit_currency == 'GHc'){//Covert to dollar
                deposit_value = deposit_value / usd_rate;
            }
            else if(currency == 'GHc' && deposit_currency == '$'){//Convert to Cedi
                deposit_value = deposit_value * usd_rate;
            }
            $('#form #deposit_conversion_rate_txt span b').html(''+currency+' '+jLib.formatNumber(deposit_value,'money'));
            $('#form #deposit_conversion_rate_txt').show();
            $('#form #conversion_rate_txt').show();
        }
        $('#form #deposit').val(deposit_value)

        return deposit_value
    },


    editSale:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];
        var url = $('#load-sale-url').val();
        var query = 'type=load&data-id=' + dataID;

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                if (response.code === 0) {
                    var dataObj = response.data;
                    var currency = dataObj['Sale']['currency'];
                    var deposit = dataObj['Sale']['deposit'];

                    $('#form #officer_incharge').val(dataObj['Sale']['officer_incharge']);
                    $('#form #vehicle_no').val(dataObj['Sale']['vehicle_no']);
					$('#form #purchase_type').val(dataObj['Sale']['purchase_type']);
                    $('#form #purchase_type').change();
                    $('#form #purchased_date').val(jLib.convertDate(dataObj['Sale']['purchased_date'],'ui'));
                    $('#form #currency').val(currency);
                    $('#form #currency').change();
                    $('#form #currency').attr('disabled','disabled');
                    $('#form #cost').val(dataObj['Sale']['cost']);
                    $('#form #insurance_total').val(dataObj['Sale']['insurance_total']);
                    $('#form #interest').val(dataObj['Sale']['interest']);
					$('#form #interest_rate_decimal_places').val(dataObj['Sale']['interest_rate_decimal_places']);
                    $('#form #interest_rate_decimal_places').change();
                    $('#form #duration_in_month').val(dataObj['Sale']['duration_in_month']);
                    $('#form #duration_in_month').change();
                    $('#form #tenor').val(dataObj['Sale']['tenor']);
                    $('#form #discount').val(dataObj['Sale']['discount']);
                    $('#form #deposit_currency').val(dataObj['Sale']['deposit_currency']);
                    $('#form #deposit_currency').change();
                    $('#form #original_deposit_amt').val(dataObj['Sale']['original_deposit_amt']);
                    $('#form #deposit').val(deposit);
                    $('#form #usd_rate').val(dataObj['Sale']['usd_rate']);
                    $('#form #deposit_conversion_rate_txt span b').html(''+currency+' '+jLib.formatNumber(deposit,'money'));
                    $('#form #payment_type').val(dataObj['Sale']['payment_type']);
                    $('#form #payment_type').change();
					$("#form #cheque_no").val(dataObj['Sale']['cheque_no']),
                    $('#form #comments').val(dataObj['Sale']['comments']);
                    $('#form #id').val(dataObj['Sale']['id']);

                    //console.log('DB DEPOSITE '+deposit);

                    self.getDeposit(currency, dataObj['Sale']['deposit_currency'], dataObj['Sale']['original_deposit_amt'], dataObj['Sale']['usd_rate']);

                    self.selected_row_id = dataID;

                    $.colorbox({
                        inline:true,
                        scrolling:false,
                        overlayClose:false,
                        escKey:false,
                        title:'Sales Information',
                        href:"#form-window"
                    });
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    jLib.serverError(txt);
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
                jLib.serverError();
            }
        });
    },


    save:function () {
        var self = this;

        /* Validate the form*/
        var validationStatus = $('#form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {

            jLib.showFormLoading();

            var query = 'model=Sale&row_id=' + self.selected_row_id + '&' + $('#form').serialize();
            /* Send the data to the server and handle the server response */
            var url = $("#add-edit-url").val();


            $.ajax({
                url:url,
                data:query,
                dataType:'json',
                type:'POST',
                success:function (response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                    if (response.code === 0) {
                        if(self.selected_row_id){

                            jLib.message(txt, 'success');

                            /*var cedi_amount = 0.00;
                            if ($('#form-window #form #currency').val() == '$') {
                                cedi_amount = parseFloat($('#form-window #form #amount').val()) * parseFloat($('#form-window #form #usd_rate').val());
                            }
                            else {
                                cedi_amount = $('#form-window #form #amount').val();
                            }
                            // Chnge the cell data
                            update_data = {
                                'name': $('#form-window #form #name').val(),
                                'contact_person':$('#form-window #form #contact_person').val(),
                                'phone_number': $('#form-window #form #phone_number').val(),
                                'email': $('#form-window #form #email').val(),
                                'address': $('#form-window #form #address').val(),
                                'city': $('#form-window #form #city').val()
                                //'status': $('#form-window #form #routine_status option:selected').text(),
                            };

                            jLib.updateGridData(self.objGrid, update_data);
                            //
                            jLib.highlightRow(self.objGrid);*/
                            $(self.objGrid).flexReload();
                        }
                        else{
                            $(self.objGrid).flexReload();

                        }
                        document.getElementById('form').reset();
                        $.validationEngine.closePrompt('.formError',true);
                        $.colorbox.close();
                        self.selected_row_id = null;
                    }
                    //* When there are Errors *//*
                    else if (response.code === 1) {
                        jLib.serverError(txt);
                    }

                    jLib.hideFormLoading();
                },
                error:function (xhr) {
                    console.log(xhr.responseText);
                    jLib.serverError();
                }
            });

        }
    },

    delete_:function (grid) {
        var self = this;

        var url = $('#delete-url').val();
        jLib.do_delete(url, grid);
    },

    initDataTypeMenus:function(){
        var self = this;

        $("button.data-type-menu").live('click',function(){
            var action = $(this).attr('action');
            var data_type = $(this).attr('data-type');
            var url = $("#"+action+"-url").val()+'/'+self.selected_row_id+'/'+data_type;

            window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        });

    },


    reprint_invoice:function (row_ids) {
        var self = this;

        var dataID = row_ids[0];

        //Initate print reciept
        var action = $('#print-invoice-url').val();
        var url = action+'/'+dataID;

        window.open(url,action,"menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");

    }

};

/* when the page is loaded */
$(document).ready(function () {
    EditSales.init();
});